<template>
    <rx-layout>
        <div slot="center">
            <rx-fit :isheader="isheader">
                <div slot="toolheader" border="false" foldbtn="false">
                    <div class="table-operator">
                        <rx-button
                            alias="insPortalDefAdd"
                            :butn-icon="'plus'"
                            :butn-type="'primary'"
                            :show-no-right="true"
                            @click="add"
                            >{{ $ti18('rxList.newBtn', '新建') }}
                        </rx-button>
                        <rx-button
                            alias="insPortalDefPreview"
                            :butn-icon="'edit'"
                            :butn-type="'primary'"
                            :show-no-right="true"
                            @click="previewPortalByUser"
                        >
                            {{ i18n('list.userPortal', '预览用户门户') }}
                        </rx-button>
                        <div class="in-qrCode" v-show="appId">
                            <a-button @click.stop="createQrCode">{{ i18n('list.qrCode', '二维码') }}</a-button>
                            <div class="in-qrCode-hover" ref="qrCode" id="in-qrCode-show" v-show="show">
                                <div class="qrcode" id="in-qrCode" ref="mobileQRCode"></div>
                                <a-button style="width: 100%; margin-top: 10px" type="primary" @click="myCanvasQrCode">
                                    {{ i18n('list.download', '下载图片') }}
                                </a-button>
                                <a-button style="width: 100%; margin-top: 10px" type="primary" @click="copyPath"
                                    >{{ i18n('list.copyPath', '复制连接') }}
                                </a-button>
                            </div>
                        </div>
                    </div>
                    <span class="search-btn-box" v-if="!isheader">
                        <span class="search-btn" @click.stop="searchshow"
                            ><i class="iconfont iconguolv"></i>{{ $ti18('rxList.leachBtn', '过滤') }}</span
                        >
                    </span>
                </div>
                <div
                    btnalign="right"
                    slot="searchbar"
                    v-if="fitSearch"
                    @search="search"
                    @cancel="cancel"
                    @close="closeSearchbar"
                >
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.name', '名称')">
                                    <a-input
                                        :placeholder="i18n('form.name', '名称', 'input')"
                                        v-model="queryParam.Q_NAME__S_LK"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.key', '别名')">
                                    <a-input
                                        :placeholder="i18n('form.key', '别名', 'input')"
                                        v-model="queryParam.Q_KEY__S_LK"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.isDefault', '是否默认')">
                                    <a-select
                                        :placeholder="i18n('form.isDefault', '请选择默认类型', 'select')"
                                        v-model="queryParam.Q_IS_DEFAULT__S_LK"
                                        style="width: 100%"
                                    >
                                        <a-select-option value="1">{{ i18n('list.yes', '是') }}</a-select-option>
                                        <a-select-option value="0">{{ i18n('list.no', '否') }}</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.isMobile', '手机门户')">
                                    <a-select
                                        :placeholder="i18n('form.isMobile', '手机门户', 'select')"
                                        v-model="queryParam.Q_IS_MOBILE__S_EQ"
                                        style="width: 100%"
                                    >
                                        <a-select-option value="YES">{{ i18n('list.yes', '是') }}</a-select-option>
                                        <a-select-option value="NO">{{ i18n('list.no', '否') }}</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :bordered="isBorder"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-portal/portal/core/insPortalDef/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10', '30', '40']"
                    id-field="portId"
                    @selectChange="onSelectChange"
                >
                    <span slot="exportApp">
                        {{ exportI18n('export.isExport', '导出') }}
                        <export-app />
                    </span>
                    <span slot="isMobile" slot-scope="{ text, record }">
                        <a-tag :color="isMobileMap[text].color">
                            <span>{{ isMobileMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="name" slot-scope="{ text, record }">
                        {{ $i18(record.name, '门户名称') }}
                    </span>
                    <span slot="isDefault" slot-scope="{ text, record }">
                        <a-tag :color="isDefaultMap[text || 0].color">
                            <span>{{ isDefaultMap[text || 0].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="isExport" slot-scope="{ text, record }">
                        <a-tag :color="text == 1 ? 'green' : 'red'">
                            <span>{{
                                text == 1 ? exportI18n('export.yes', '是') : exportI18n('export.no', '否')
                            }}</span>
                        </a-tag>
                    </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                        <span v-if="editEnable && showBtn(true)" @click="edit(record)">{{
                            $ti18('rxList.editBtn', '编辑')
                        }}</span>
                        <span
                            v-if="record.isMobile != 'YES' && showBtn(true)"
                            @click="setPortalLayout(record.portId)"
                            :title="i18n('list.setPortalLayout', '布局设计')"
                            >{{ i18n('list.setPortalLayout', '布局设计') }}</span
                        >
                        <span v-if="record.isMobile != 'YES' && showBtn(true)" @click="Preview(record)">{{
                            $ti18('rxList.previews', '预览')
                        }}</span>
                        <span v-else @click="setMobilePortal(record.portId)">{{ i18n('list.devise', '设计') }}</span>
                        <span v-if="editEnable && showBtn(true)" @click="editPermission(record.portId)">{{
                            i18n('list.editPermission', '权限编辑')
                        }}</span>
                        <span
                            v-if="editEnable && record.isMobile == 'NO' && showBtn(true)"
                            @click="deployMenu(record)"
                            >{{ $ti18('rxList.deployMenu', '发布菜单') }}</span
                        >
                        <span v-if="removeEnable && showBtn(true)" @click="delByIds([record.portId])">{{
                            $ti18('rxList.delBtn', '删除')
                        }}</span>
                        <span @click="setExport(record, exportConf)">{{
                            record.isExport == 1
                                ? exportI18n('export.noExport', '不导出')
                                : exportI18n('export.exported', '导出')
                        }}</span>
                    </span>
                </rx-grid>
            </rx-fit>
            <a-modal
                :title="i18n('list.selectInit', '选择用户')"
                style="top: 100px"
                :width="400"
                v-model="visible"
                :confirmLoading="false"
                @ok="handleOk"
            >
                <rx-user-component :single="true" v-model="previewUser" style="width: 100%"></rx-user-component>
            </a-modal>
        </div>
    </rx-layout>
</template>

<script>
import InsPortalDefApi from '@/api/portal/core/insPortalDef'
import InsPortalPermissionApi from '@/api/portal/core/insPortalPermission'
import InsPortalDefEdit from './InsPortalDefEdit'
import switchExport from '@/utils/switchExport'
import { BaseList, RxLayout, Util } from '@lowcode/jpaas-common-lib'
import InsPortalLayoutEdit from './InsPortalLayoutEdit.vue'
import PermissionDialog from '@/views/modules/share/PermissionDialog'
import InsPortalMobileEdit from './InsPortalMobileEdit.vue'
import DialogBox from '@/assets/js/DialogBox'
import FormCustomEdit from '../../form/core/FormCustomEdit'
import { mapState } from 'vuex'
import PublicApi from '@/api/system/core/public'
import exportApp from '@/views/modules/share/exportApp'
import DialogView from '@/layouts/DialogView'

export default {
    name: 'InsPortalDefList',
    mixins: [BaseList, switchExport],
    components: {
        InsPortalLayoutEdit,
        PermissionDialog,
        RxLayout,
        exportApp,
    },
    props: ['currentApp'],
    computed: {
        ...mapState({
            user: (state) => (state.appSetting ? state.appSetting.user : {}),
        }),
    },
    data() {
        return {
            columns: [
                {
                    title: '序号',
                    dataIndex: 'serial',
                    type: 'indexColumn',
                    scopedSlots: { customRender: 'serial' },
                    width: 40,
                },
                {
                    title: this.i18n('form.name', '名称'),
                    dataIndex: 'name',
                    width: 180,
                    scopedSlots: { customRender: 'name' },
                },
                { title: this.i18n('form.key', '别名'), dataIndex: 'key', width: 120 },
                {
                    title: this.i18n('form.default', '默认'),
                    dataIndex: 'isDefault',
                    width: 80,
                    scopedSlots: { customRender: 'isDefault' },
                },
                {
                    title: this.i18n('form.isMobile', '手机门户'),
                    dataIndex: 'isMobile',
                    width: 80,
                    scopedSlots: { customRender: 'isMobile' },
                },
                { title: this.i18n('form.priority', '优先级'), dataIndex: 'priority', width: 60 },
                {
                    dataIndex: 'isExport',
                    slots: { title: 'exportApp' },
                    width: 60,
                    scopedSlots: { customRender: 'isExport' },
                },
                { title: this.$ti18('rxForm.createTime', '创建时间'), dataIndex: 'createTime', width: 120 },
                {
                    title: this.$ti18('rxList.action', '操作'),
                    dataIndex: 'action',
                    width: Util.langSize({ 'zh-CN': 120, 'en-US': 200, 'ja-JP': 200, 'es-ES': 200 }),
                    size: 2,
                    scopedSlots: { customRender: 'action' },
                },
            ],
            component: InsPortalDefEdit,
            comment: this.i18n('list.comment', '门户定义'),
            widthHeight: ['650px', '550px'],
            isDefaultMap: {
                1: { color: 'green', text: this.i18n('list.yes', '是') },
                0: { color: 'red', text: this.i18n('list.no', '否') },
            },
            isMobileMap: {
                YES: { color: 'green', text: this.i18n('list.yes', '是') },
                NO: { color: 'red', text: this.i18n('list.no', '否') },
            },
            portId: '',
            portalLayoutShow: true,
            appId: '',
            path: '/mobile/pages/RxAppPortal/RxAppPortal',
            show: false,
            i18nDefault: process.env.VUE_APP_LANGUAGE,
            i18nCurrent: '',
            /**
             * 导出配置
             */
            exportConf: {
                Api: InsPortalDefApi,
                id: 'pkId',
            },
            loading: false,
            visible: false,
            previewUser: [],
        }
    },
    created() {
        this.getCurrentI18n()
        this.getServerAddress()
        this.appId = this.curApp.appId
        this.needFilterAppId()
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, 'insPortalDef', key)
        },
        exportI18n(name, text, key) {
            return this.$ti18(name, text, 'appExport', key)
        },
        getCurrentI18n() {
            this.i18nCurrent = window.localStorage.getItem('language')
            if (!this.i18nCurrent) {
                this.i18nCurrent = this.i18nDefault
            }
        },
        deployMenu(record) {
            let component = 'modules/portal/PortalLayoutPreview/PortalLayoutPreview.vue'
            DialogBox.openDeploymenuDialog(
                {
                    releaseId: record.id,
                    name: record.name,
                    mKey: record.key + 'Portal',
                    params: { alias: record.key },
                    component: component,
                    curAppObj: this.curApp,
                },
                {
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                }
            )
        },
        async editPermission(portId) {
            if (this.loading) {
                return
            }
            let permission = { type: 'ALL', typeList: [] }
            this.loading = true
            let data = await InsPortalPermissionApi.getListByLayoutId(portId)
            if (data.success) {
                permission = data.data
            }
            this.loading = false
            var conf = {
                component: PermissionDialog,
                title: this.i18n('list.permissionTitle', '门户权限设计'),
                widthHeight: ['850px', '500px'],
            }
            var self_ = this
            var baseConf = {
                curVm: self_,
                data: {
                    permission: permission,
                },
            }
            let config = Object.assign(baseConf, conf)

            Util.open(config, function (action, data) {
                if (action != 'ok') {
                    return
                }
                var params = {
                    layoutId: portId,
                    menuType: 'portal',
                    type: data.type,
                }
                if ('custom' == data.type) {
                    params.typeList = data.typeList
                }
                var self_ = this
                InsPortalPermissionApi.saveAll(params).then((res) => {
                    self_.$message.success(res.data)
                })
            })
        },
        delById(ids) {
            return InsPortalDefApi.del({ ids: ids.join(',') })
        },
        getListByParams(parameter) {
            return InsPortalDefApi.query(parameter)
        },
        setPortalLayout(portId) {
            this.portalLayoutShow = true
            this.portId = portId
            var self_ = this
            var config = {
                curVm: self_,
                component: FormCustomEdit,
                title: this.i18n('list.layoutTitle', '门户布局设计'),
                max: true,
                data: {
                    pkId: portId,
                    portalLayout: true,
                },
            }
            Util.open(config, function (action) {
                self_.$refs.table.loadData()
            })
        },
        setMobilePortal(pk) {
            var conf = {
                component: InsPortalMobileEdit,
                title: this.i18n('list.portalMobileTitle', '编辑移动门户'),
            }
            var self_ = this
            var baseConf = {
                curVm: self_,
                data: {
                    pkId: pk,
                    callback: function (data) {
                        console.info(data)
                    },
                },
                max: true,
            }
            let config = Object.assign(baseConf, conf)
            Util.open(config, function (action) {})
        },
        search() {
            this.$refs.table.loadData()
        },
        cancel() {
            this.resetSearch()
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false
        },
        getServerAddress() {
            PublicApi.getSysAppConfigs().then((res) => {
                if (res && res.serverAddress) {
                    this.path =
                        res.serverAddress +
                            this.path +
                            '?appId=' +
                            this.curApp.appId +
                            '&appName=' +
                            this.curApp.appName || ''
                }
            })
        },
        createQrCode() {
            var self = this
            this.show = !this.show
            if (!this.show) {
                return
            }
            setTimeout(() => {
                self.$refs.mobileQRCode.innerHTML = ''
                var qrcode = new QRCode(self.$refs.mobileQRCode, {
                    text: self.path, // 需要转换为二维码的内容
                    width: 130,
                    height: 130,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.H,
                })
            }, 200)
        },
        myCanvasQrCode() {
            let base64Img = document.getElementById('in-qrCode').getElementsByTagName('canvas')[0].toDataURL()
            let link = document.createElement('a')
            link.href = base64Img
            link.download = 'code' + Date.now()
            let event = document.createEvent('MouseEvents')
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
            link.dispatchEvent(event)
        },
        copyPath() {
            let tag = document.createElement('input')
            tag.setAttribute('id', 'copyInput')
            tag.value = this.path
            document.getElementsByTagName('body')[0].appendChild(tag)
            document.getElementById('copyInput').select()
            document.execCommand('copy')
            document.getElementById('copyInput').remove()
            this.$message.success(this.i18n('msa.copyTips', '复制成功'))
        },
        checkClick(event) {
            let dom = this.$refs.qrCode
            if (!dom.contains(event.target)) {
                // 不在菜单范围，隐藏即可
                if (this.show) {
                    this.show = false
                    document.removeEventListener('click', this.checkClick)
                }
            }
        },
        Preview(record) {
            let ctxPath = process.env.VUE_APP_CONTEXT_MAIN
            let url = ctxPath + '/PortalLayoutPreview/' + record.key
            let appId = record.appId
            if (appId) {
                url += '?appId=' + appId
            }
            let conf = {
                component: DialogView,
                curVm: this,
                max: true,
                title: record.name ? this.$i18(record.name) : this.i18n('list.previewTitle', '自定义页面预览'),
                data: {
                    url: url,
                },
            }
            Util.open(conf)
        },
        previewPortalByUser() {
            this.previewUser = [{ id: this.user.userId, name: this.user.fullName }]
            this.visible = true
        },
        handleOk() {
            if (this.previewUser.length == 0 || !this.previewUser[0].id) {
                this.$message.error(this.i18n('msa.selectInitor', '请选择用户！'))
                return
            }
            this.visible = false
            if (this.appId) {
                InsPortalDefApi.getCurUserPortalByAppIdAndUserId(this.appId, this.previewUser[0].id).then((res) => {
                    if (!res || !res.key) {
                        this.$message.error(this.i18n('msa.noexistPortal', '当前用户不存在门户'))
                        return
                    }
                    // 进入门户预览
                    this.Preview(res)
                })
            } else {
                InsPortalDefApi.getOwnPortalDefByUserId(this.previewUser[0].id).then((res) => {
                    if (!res || !res.key) {
                        this.$message.error(this.i18n('msa.noexistPortal', '当前用户不存在门户'))
                        return
                    }
                    // 进入门户预览
                    this.Preview(res)
                })
            }
        },
    },
    watch: {
        show: {
            handler(newVal, olVal) {
                if (newVal) {
                    setTimeout(() => {
                        document.addEventListener('click', this.checkClick)
                    }, 0)
                } else {
                    document.removeEventListener('click', this.checkClick)
                }
            },
        },
    },
}
</script>
<style scoped>
.in-qrCode-hover-path {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.in-qrCode {
    float: right;
    position: relative;
}

.in-qrCode-hover {
    position: absolute;
    width: 150px;
    left: -40px;
    top: 37px;
    z-index: 99;
    background-color: #ffffff;
    box-shadow: 0px 0px 13px 0px rgba(6, 0, 1, 0.17);
    border: solid 1px #eeeeee;
    border-radius: 5px;
    padding: 10px;
}
</style>
